package com.ruoyi.web.controller.customer;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.api.domain.ApiManage;
import com.ruoyi.api.domain.AppManage;
import com.ruoyi.api.domain.RecRecord;
import com.ruoyi.api.service.IApiManageService;
import com.ruoyi.api.service.IAppManageService;
import com.ruoyi.api.service.IRecRecordService;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.detection.DetectionService;
import com.ruoyi.common.utils.detection.DetectionService.DetectionResult;

/**
 * 手动检测Controller
 * 
 * @author ruoyi
 * @date 2025-01-15
 */
@RestController
@RequestMapping("/customer/manualDetection")
public class CustomerManualDetectionController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(CustomerManualDetectionController.class);
    
    @Autowired
    private IAppManageService appManageService;
    
    @Autowired
    private IApiManageService apiManageService;
    
    @Autowired
    private IRecRecordService recRecordService;
    
    /**
     * 手动上传图片进行检测
     * 
     * @param appId 应用ID
     * @param file 上传的图片文件
     * @return 检测结果
     */@Log(title = "手动检测", businessType = BusinessType.INSERT)
    @PostMapping("/upload")
    public AjaxResult uploadAndDetect(@RequestParam("appId") Long appId,
                                     @RequestParam("file") MultipartFile file)
    {
        try
        {
            // 参数验证
            if (appId == null)
            {
                return error("应用ID不能为空");
            }
            
            if (file == null || file.isEmpty())
            {
                return error("请选择要上传的图片文件");
            }
            
            // 验证文件类型
            String originalFileName = file.getOriginalFilename();
            if (StringUtils.isEmpty(originalFileName))
            {
                return error("文件名不能为空");
            }
            
            String fileExtension = originalFileName.substring(originalFileName.lastIndexOf('.') + 1).toLowerCase();
            if (!isValidImageExtension(fileExtension))
            {
                return error("只支持jpg、jpeg、png、gif、bmp格式的图片文件");
            }
            
            // 验证文件大小（限制为10MB）
            if (file.getSize() > 10 * 1024 * 1024)
            {
                return error("文件大小不能超过10MB");
            }
            
            log.info("开始处理手动上传检测，应用ID: {}, 文件名: {}, 文件大小: {} bytes", 
                    appId, originalFileName, file.getSize());
            
            // 获取应用信息
            AppManage appManage = appManageService.selectAppManageByAppId(appId);
            if (appManage == null)
            {
                return error("应用不存在");
            }
            
            // 验证应用是否属于当前用户
            try {
                String username = getUsername();
                if (!username.equals(appManage.getCreateBy()))
                {
                    return error("无权限使用此应用");
                }
            } catch (Exception e) {
                return error("获取用户信息失败，请确保您的登录状态有效");
            }
            
            // 获取关联的API信息
            ApiManage apiManage = apiManageService.selectApiManageByApiId(appManage.getApiId());
            if (apiManage == null)
            {
                return error("关联的API不存在");
            }
            
            // 保存上传的图片到本地
            String localImagePath = DetectionService.saveUploadedImage(
                file.getBytes(), 
                originalFileName, 
                "manual_" + appId
            );
            
            if (StringUtils.isEmpty(localImagePath))
            {
                return error("图片保存失败");
            }
            
            log.info("图片保存成功，本地路径: {}", localImagePath);
            
            // 调用检测API
            String apiUrl = apiManage.getApiUrl();
            if (StringUtils.isEmpty(apiUrl))
            {
                return error("检测API地址为空");
            }
            
            // 将相对路径转换为绝对路径用于检测
            String absoluteImagePath = com.ruoyi.common.config.RuoYiConfig.getProfile() + localImagePath;
            
            String response = DetectionService.detectImage(apiUrl, absoluteImagePath);
            
            if (StringUtils.isEmpty(response))
            {
                return error("检测API调用失败");
            }
            
            // 解析检测结果
            DetectionResult detectionResult = DetectionService.parseDetectionResponse(response);
            
            if (!detectionResult.isSuccess())
            {
                return error("检测失败，请检查图片格式或重试");
            }
            
            // 创建识别记录
            RecRecord recRecord = new RecRecord();
            recRecord.setAppId(appManage.getAppId());
            recRecord.setDeviceId(appManage.getDeviceId());
            recRecord.setInputImg(localImagePath);
            recRecord.setRecResult(detectionResult.getRawResponse());
            recRecord.setTaskType("手动");
            recRecord.setProcessStatus("已完成");
            recRecord.setCreateTime(new Date());
            
            // 设置创建者，处理可能的异常
            try {
                recRecord.setCreateBy(getUsername());
            } catch (Exception e) {
                recRecord.setCreateBy(appManage.getCreateBy()); // 使用应用创建者作为备选
            }
            
            // 设置检测结果信息
            if (detectionResult.getConfidence() != null)
            {
                recRecord.setConfidence(detectionResult.getConfidence());
            }
            if (detectionResult.getConfThreshold() != null)
            {
                recRecord.setConfThreshold(detectionResult.getConfThreshold());
            }
            if (detectionResult.getDanger() != null)
            {
                recRecord.setDanger(detectionResult.getDanger());
            }
            
            // 保存到数据库
            int result = recRecordService.insertRecRecord(recRecord);
            if (result > 0)
            {
                log.info("手动检测成功，应用ID: {}, 记录ID: {}, 是否预警: {}", 
                        appId, recRecord.getRecordId(), recRecord.getDanger());
                
                // 返回检测结果
                return success( recRecord);
            }
            else
            {
                log.error("保存识别记录失败，应用ID: {}", appId);
                return error("保存检测结果失败");
            }
        }
        catch (Exception e)
        {
            log.error("手动检测异常，应用ID: {}, 异常信息: {}", appId, e.getMessage(), e);
            return error("检测过程中发生异常: " + e.getMessage());
        }
    }
    
    /**
     * 验证图片文件扩展名
     * 
     * @param extension 文件扩展名
     * @return 是否为有效的图片扩展名
     */
    private boolean isValidImageExtension(String extension)
    {
        String[] validExtensions = {"jpg", "jpeg", "png", "gif", "bmp"};
        for (String validExt : validExtensions)
        {
            if (validExt.equals(extension))
            {
                return true;
            }
        }
        return false;
    }
}